package com.oocl.training.clean.impl;

import com.oocl.training.clean.Cleanable;
import com.oocl.training.exception.ParameterErrorException;
import com.oocl.training.pojo.Customer;
import com.oocl.training.util.PatternUtil;

/**
 * 用户清洗
 * @author GANAB
 *
 */
public class CleanCustomer implements Cleanable<Customer, String>{
	
	/**
	 * 清洗脏数据，返回用户列表
	 * @throws ParameterErrorException 
	 */
	public Customer clean(String t) throws ParameterErrorException {
		if(t!=null){
			t = t.trim();
			String[] fields = t.split(" ");
			//去除空格和Tab符
			for(int i = 0; i < fields.length; i++){
				fields[i] = fields[i].trim();
			}
			//判断是否为5个，否则抛出异常
			if(fields.length != 5){
				throw new ParameterErrorException("Customer参数不足，请检查是否满足id name email sex birthday格式");
			}
			//校验格式，不满足返回null
			if(!fields[0].matches(PatternUtil.ID_REX) || !fields[1].matches(PatternUtil.NAME_REX) || !fields[2].matches(PatternUtil.EMAIL_REX)
					|| !fields[3].matches(PatternUtil.SEX_REX) || !fields[4].matches(PatternUtil.BIRTHDAY_REX)){
				return null;
			}
			
			Customer customer = new Customer();
			customer.setId(fields[0]);
			customer.setName(fields[1]);
			customer.setEmail(fields[2]);
			customer.setSex(("true".equals(fields[3])) ? "男" : "女");
			customer.setBirthday(birthdayFormat(fields[4]));
			
			return customer;
		}
		
		return null;
	}
	
	private String birthdayFormat(String s){
		return s.replace("/", "-");
	}

}
